package com.ftg.learn.execl.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.ftg.learn.execl.domain.StudentDomain;
import com.ftg.learn.execl.util.ExeclUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 布衣
 */
@Slf4j
@Service
public class ExcelService {

    @Resource
    RedisTemplate<String, String> redisTemplate;

    private Lock lock = new ReentrantLock();

    public String readAllSheets(String filePath) {

        try {
            lock.lock();
            log.info("开始读取所有工作表的Excel文件");
            //从所有sheet
            ExeclUtil listener = new ExeclUtil();
            EasyExcel.read(filePath, StudentDomain.class, listener).sheet().headRowNumber(5).doRead();

            //listener.getDataList()转换成为json结构字符串
            Gson gson = new Gson();
            String json = gson.toJson(listener.getDataList());
            //连接redis - 存储redis中
            HashOperations<String, String, String> stringObjectObjectHashOperations = redisTemplate.opsForHash();
            String k = Md5Crypt.apr1Crypt(filePath, "123");
            if (StringUtils.isEmpty(stringObjectObjectHashOperations.get(k, "sheet01"))) {
                stringObjectObjectHashOperations.put(k, "sheet01", json);
                stringObjectObjectHashOperations.put("record", k + "_" + "sheet01", "unread");
            }
            return "success";
        } catch (Exception e) {
            lock.unlock();
            log.error("读取所有工作表的Excel失败", e);
            return "读取所有工作表的Excel失败" + e.getMessage();
        } finally {
            lock.unlock();
        }
    }
}
